package com.kolon.business.mngr.banner.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.business.mngr.banner.dao.BannerDao;
import com.kolon.framework.constant.Constant;
import com.kolon.framework.file.DefaultFileRenamePolicy;
import com.kolon.framework.file.FileUtil;
import com.kolon.framework.file.UploadedFile;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mngr.banner.controller.BannerWriteController")
public class BannerWriteController implements SimpleController {

	@Resource(name="com.kolon.business.mngr.banner.dao.BannerDaoImpl")
	private BannerDao bannerDao;
	
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/business/mngr/banner/bannerWrite.do")
	public ModelAndView controller(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Map<String, String> map = new HashMap<String, String>();
		UploadedFile imgFile = null;
		// 파라미터
		map.put("bnerNm", ComUtil.nullChk(multiRequest.getParameter("bnerNm"), "없음"));
		map.put("bnerDesc", ComUtil.nullChk(multiRequest.getParameter("bnerDesc")));
		map.put("lnkUrl", multiRequest.getParameter("lnkUrl"));
		map.put("useYn", ComUtil.nullChk(multiRequest.getParameter("useYn"), "Y"));
		// 회원 세션 정보
		HttpSession httpSession = multiRequest.getSession();
		Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_MNGR_INFO);
		map.put("rgstId", (String)userMap.get("MNGR_ID"));
		// 배너 이미지 저장 경로
		String bannerPath = MsgUtil.getMessage("banner.path");
		// STEP START
		try {
			// STEP 01. 이미지 파일 업로드
			imgFile = FileUtil.fileUpload(multiRequest.getFile("imgNm"), bannerPath, 
					new DefaultFileRenamePolicy());
			map.put("imgNm", imgFile.getFileName());
			// STEP 02. 시퀀스 값 조회
			map.put("bnerNo", ComUtil.oTos(bannerDao.getMax().get("BNER_NO")));
			// STEP 03. 정보 등록
			bannerDao.insert(map);
		} catch (Exception e) {
			// 예외 발생 시 업로드 된 파일을 삭제
			if (imgFile != null)
				FileUtil.delFile(bannerPath + imgFile.getFileName());
		}
		// 리턴
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("redirect:/business/mngr/banner/bannerList.do");
		return modelAndView;
	}
}
